package com.yboot.starter.mybatis.core.base.controller;

import cn.hutool.core.collection.ListUtil;
import com.yboot.starter.common.core.web.page.PageVO;
import com.yboot.starter.common.core.web.validation.InsertGroup;
import com.yboot.starter.common.core.web.validation.UpdateGroup;
import com.yboot.starter.common.core.web.vo.Result;
import com.yboot.starter.mybatis.core.base.query.PageQuery;
import com.yboot.starter.mybatis.core.base.service.IBaseService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Controller抽象基类
 *
 * @param <S> 业务接口
 * @param <L> 列表类型
 * @param <D> 详情类型
 * @param <Q> 查询条件类型
 * @param <C> 创建或修改请求参数类型
 * @author yangcs
 * @date 2025/8/29
 */
public abstract class BaseController <S extends IBaseService<T, L, D, Q, C>, T, L, D, Q extends PageQuery, C> {

    @Autowired
    protected S baseService;

    /**
     * 分页查询列表
     */
    @ResponseBody
    @PostMapping("/page")
    public Result<PageVO<L>> page(@RequestBody Q query) {
        return Result.ok(baseService.queryPage(query));
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @PostMapping("/list")
    public Result<List<L>> list(@RequestBody Q query) {
        return Result.ok(baseService.list(query));
    }

    /**
     * 新增
     */
    @ResponseBody
    @PostMapping
    public Result<String> save(@Validated(InsertGroup.class) @RequestBody C req) {
        return Result.ok(baseService.saveInfo(req));
    }

    /**
     * 修改
     */
    @ResponseBody
    @PutMapping
    public Result<Void> update(@Validated(UpdateGroup.class) @RequestBody C req) {
        baseService.updateInfo(req);
        return Result.ok();
    }

    /**
     * 查询详情
     */
    @Parameter(name = "id", description = "ID主键", example = "1", in = ParameterIn.PATH)
    @ResponseBody
    @GetMapping("/{id}")
    public Result<D> detail(@PathVariable("id") String id) {
        return Result.ok(baseService.detail(id));
    }

    /**
     * 删除
     */
    @Parameter(name = "id", description = "ID主键", example = "1", in = ParameterIn.PATH)
    @ResponseBody
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable("id") String id) {
        baseService.delete(ListUtil.of(id));
        return Result.ok();
    }


    /**
     * 根据返回结果
     */
    public Result toResult(Boolean result) {
        return result ? Result.ok() : Result.error("请求失败");
    }
}
